package Chat;

import iterfaces.Ships;

import java.net.*;

import java.io.*;
import java.util.Scanner;

import javax.swing.JOptionPane;

import controllers.DataInsertion;
import controllers.Map;

import windows.GameConsole;
import windows.GameLobby;

public class A_Chat_Client implements Runnable
{
	static private Ships ship;
	//GLOBALS
	Socket SOCK;
	Scanner INPUT;
	Scanner SEND = new Scanner(System.in);
	PrintWriter OUT;
	public boolean hasConnected = false;
	
	public A_Chat_Client(Socket X)
	{
		this.SOCK = X;
	}
	
	public void run()
	{
		try
		{
			try
			{
				INPUT = new Scanner(SOCK.getInputStream());
				OUT = new PrintWriter(SOCK.getOutputStream());
				OUT.flush();
				hasConnected = true;
				CheckStream();
			}
			finally
			{
				SOCK.close();
			}
		}
		catch(Exception X) {System.out.println(X);}
	}
	
	public void DISCONNECT() throws IOException
	{
		OUT.println(GameConsole.UserName + " has disconnected");
		OUT.flush();
		SOCK.close();
		JOptionPane.showMessageDialog(null, "You disconnected!");
		System.exit(0);
	}
	
	public void CheckStream()
	{
		while(true)
		{
			RECEIVE();
		}
	}
	
	public void RECEIVE()
	{
		if(INPUT.hasNext())
		{
			String MESSAGE = INPUT.nextLine();
			
			if (MESSAGE.contains("#?!"))
			{
				String  TEMP1 = MESSAGE.substring(3);
				 		TEMP1 = TEMP1.replace("[", "");
				 		TEMP1 = TEMP1.replace("]", "");
				 		
				String[] CurrentUsers = TEMP1.split(", ");
				
				GameConsole.JL_ONLINE.setListData(CurrentUsers);
			}
			else if(MESSAGE.contains("$@"))
			{				
				String TEMP2 = MESSAGE.substring(2);
				Map.getMap().addDrawAbleShipInfo(TEMP2);
			}
			else if (MESSAGE.contains(GameLobby.groupName))
			{
				GameConsole.TA_CONVERSATION.append(MESSAGE + "\n");
				GameConsole.TA_CONVERSATION.setCaretPosition(GameConsole.TA_CONVERSATION.getDocument().getLength());
			}
			else
			{
				
			}
		}
	}
	
	public void SEND(String X)
	{
		OUT.println(GameLobby.groupName +" "+ GameConsole.UserName + ": " + X); //CHAT
		OUT.flush(); //CHAT
		GameConsole.TF_Message.setText(""); //CHAT
		DataInsertion.LogInsert(GameConsole.UserName.toString(), "Chat: " + X.toString()); //DATABASE
	}	
	
	public void SENDGAMEDATA (String X)
	{
		OUT.println("$@" + X);
		OUT.flush();
	}
}
